<template>
  <div class="app-container otherCss">
    <div id="mainContainer" class="up s-border">
      <!-- 视频播放器，截图用 -->
      <live-video-area-view
        v-if="video && video.sourceUrl"
        id="mainPlayer"
        ref="mainPlayer"
        :url="video.sourceUrl"
        :muted="true"
        style="width: 300px; height: 200px;display:none;"/>
    </div>
    <!-- 视频截图临时容器 -->
    <div class="videobox" style="display:block;width:100%;height:100%;position:absolute;z-index:-1;opacity:0;"/>
    <div class="btnbox">
      <el-button type="primary" @click="newUplaod">新建上传</el-button>
    </div>
    <el-form label-position="left" label-width="100px">
      <el-form-item label="发布人">
        <el-select v-model="listUpload.bizType" class="select" placeholder="请选择上传类型">
          <el-option
            v-for="item in bizTypeFormat"
            :key="item.key"
            :label="item.value"
            :value="item.key"/>
        </el-select>
      </el-form-item>
      <el-form-item label="期数ID">
        <el-input v-model="playId" clearable class="" style="width:220px;" placeholder="请输入期数ID">
          <el-button slot="append" icon="el-icon-search" @click="getSearch"/>
        </el-input>
      </el-form-item>
      <el-form-item v-show="listUpload.bizType==3" label="主持人ID">
        <el-input v-model="hostId" clearable class="" style="width: 200px;" placeholder="请输入主持人ID"/>
      </el-form-item>
      <el-form-item label="节目分类">
        <el-select v-model="listUpload.lenType" class="select" placeholder="请选择">
          <el-option
            v-for="item in lenTypeFormat"
            :key="item.key"
            :label="item.value"
            :value="item.key"/>
        </el-select>
      </el-form-item>
      <el-form-item label="地区">
        <el-cascader
          v-model="listUpload.loc"
          :options="cityList"
          :props="{
            expandTrigger: 'hover',
            value:'id',
            label:'name'
          }"
        />
      </el-form-item>
    </el-form>
    <div>
      <el-upload
        ref="upload"
        :show-file-list="false"
        :file-list="listBox"
        :multiple="true"
        :on-change="change"
        :auto-upload="false"
        :on-progress="progress"
        :on-success="successUpload"
        :on-error="onError"
        :headers="headers"
        :action="upload_url"
        :http-request="uploadBySelf"
        accept=".mp4"
        class="upload-demo"
      >
        <el-button slot="trigger" type="primary">选取素材</el-button>
        <el-button style="margin-left: 10px;" type="success" @click="submitUpload">一键上传</el-button>

      </el-upload>
    </div>
    <div v-show="listBox.length>0" id="tablelist">
      <table style="width:100%">
        <tr style="width:100%;">
          <th style="width:400px;">素材名称</th>
          <th>时长</th>
          <th>大小</th>
          <th>状态</th>
          <th>关键字</th>
          <th>标签</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in listBox" :key="index" :style="{color:item.status=='fail'?'#F56C6C':''}" style="width:100%;">
          <td>{{ item.name }}</td>
          <td>{{ item.duration }}</td>
          <td>{{ parseFloat(( item.size / 1024 / 1024)).toFixed(2) + 'MB' }}</td>
          <td v-show="item.status=='ready'">等待上传</td>
          <td v-show="item.status=='success'&&item.percentage==100">上传成功</td>
          <td v-show="item.status=='fail'">上传失败</td>
          <td v-show="item.status=='uploading'">上传中 {{ item.percentage|toInt }} %</td>
          <td >
            <el-input v-model="item.keywords" type="textarea" style="max-width:250px;" resize="none" placeholder="多个关键字用逗号隔开"/>
          </td>
          <td >
            <el-cascader
              v-model="item['cateList']"
              :options="cateOptions"
              :collapse-tags="true"
              :props="{
                expandTrigger: 'hover',
                value:'id',
                label:'name',
                multiple: true
              }"
            />
          </td>
          <td>
            <el-tag :disable-transitions="true" style="cursor:pointer;" @click="del_video(item,index)">删除</el-tag>
            <el-tag v-show="item.status=='fail'" :disable-transitions="true" type="danger" style="cursor:pointer;" @click="reUpload(item,false)">重新上传</el-tag>

          </td>
        </tr>
      </table>
    </div>
    <!-- 测试封面图 -->
    <!-- <div>
      <p style="display:inline-block;" v-for="(item, index) in test" :key="index">
        <span style="display:block;">{{item.n}}</span>
        <span style="display:inline-block;width:200px;height:350px;"><img style="width:100%;height:100%;" :src="item.u" alt=""></span>
      </p>
    </div> -->
  </div>
</template>
<script>

import BackToTop from '../../../components/BackToTop'
import ObjectUtil from '../../../utils/object-util'
import timeUtil from '../../../utils/time-util'
import { apiMeterial } from '../../../api/mediaManage/index'
import { apiUpload } from '../../../api/upload'
import { apiCommon } from '../../../api/common'
import { getToken } from '../../../utils/auth'
import Fn from '../../../utils/fn'
import LiveVideoAreaView from '../clip/views/LiveVideoAreaView'
import { FileUtil } from '../../../utils/file-util'
import Common from '../../../utils/common'
import request from '@/utils/request'
import BaseUrl from '../../../api/BaseUrl'
import { bizTypeFormat, lenTypeFormat } from '../../../mixin/MixinContants'
const systemPath = BaseUrl.getDefaultBaseUrl()
const modulePath = systemPath + '/api-file'

export default {
  name: 'RadioProgramList',
  inject: ['reload'],
  components: {
    BackToTop,
    LiveVideoAreaView
  },
  filters: {
    toInt(val) {
      return Number(val.toFixed(0))
    }
  },

  mixins: [
    bizTypeFormat.mixin,
    lenTypeFormat.mixin
  ],
  data() {
    return {
      defaultkeywords: '',
      // 分类表
      cateOptions: [],
      // 搜索绑定的分类
      cateList: [],
      // 地区表
      cityList: [],
      defaultLabel: '',
      headers: { 'Authorization': 'Bearer ' + getToken() },
      upload_url: '',
      listBox: [],
      video: { sourceUrl: undefined },
      // 主持人id
      hostId: undefined,
      // 期数ID
      playId: '',
      listUpload: {
        type: '1',
        source: '3',
        bizType: 1,
        lenType: 0,
        loc: []
        // cateList: []
        // keywords: ''

        // auditStatus: '0'
      },
      duration: '',
      uploadList: [],
      count: 0,
      // 上传锁，正在上传加锁，上传完解锁
      uploading: false,
      loading: null,
      test: []

    }
  },
  created() {
    this.Init()
    this.upload_url = apiUpload.upload_url
    this.$delete(this.bizTypeFormat, '7') // 7是频率上传，媒资用不到
  },
  methods: {
    // 地区格式化
    formatLoc(loc) {
      let cityInfo = []
      this.cityList && this.cityList.forEach(p => {
        p.children && p.children.forEach(c => {
          if (c.id == loc) {
            cityInfo = [p.id, c.id]
          }
        })
      })
      return cityInfo
    },
    /**
     * 格式化分类数据
     * @argument type 1[[...],[...]] to 一级:[],二级:[]  2一级:[],二级:[] to [[...],[...]]
    */
    formatCate(type, cateList) {
      let cateInfo = null
      let filterData = null
      if (type == 1) {
        filterData = [...new Set([].concat(...cateList))]
        cateInfo = { cateOneList: [], cateTwoList: [] }
        filterData.forEach(item => {
          this.cateOptions.forEach(cate => {
            if (item == cate.id) {
              cateInfo.cateOneList.push({ ...cate })
            } else {
              cate.children && cate.children.forEach(c => {
                if (item == c.id) {
                  cateInfo.cateTwoList.push({ ...c })
                }
              })
            }
          })
        })
      } else {
        cateInfo = []
        cateList && cateList.forEach(item => {
          item.children.forEach(c => {
            cateInfo.push([item.id, c.id])
          })
        })
      }
      return cateInfo
    },
    // tree结构格式化，去二级children
    formatList(list) {
      list.forEach(item => {
        item.children.forEach(c => {
          c.children = undefined
        })
      })
      return list
    },
    // 省市信息
    getAreaList() {
      return new Promise((resolve, reject) => {
        apiCommon.arealist().then(res => {
          if (res.data.resp_code == 0) {
            this.cityList = this.formatList(res.data.datas)
            resolve(res.data.datas)
          } else {
            this.toast.fail(res.data.resp_msg)
            reject(res)
          }
        }).catch(response => {
          this.$notify.error({
            title: '失败',
            message: (response.data.resp_msg || {})['errmsg'] || '请联系系统管理员'
          })
          reject(response)
        })
      })
    },
    // 获取关联的分类信息
    relationCategory() {
      return new Promise((resolve, reject) => {
        apiMeterial.relationCategory().then(res => {
          if (res.data.resp_code == 0) {
            this.cateOptions = this.formatList(res.data.datas)
            resolve(res.data.datas)
          } else {
            this.toast.fail(res.data.resp_msg)
            reject(res.data)
          }
        }).catch(response => {
          this.$notify.error({
            title: '失败',
            message: (response.data.resp_msg || {})['errmsg'] || '请联系系统管理员'
          })
          reject(response)
        })
      })
    },
    // 重新上传
    reUpload(item, next) {
      if (this.uploading) {
        return this.toast.fail('有任务正在上传，稍后再试')
      }
      this.uploadBySelf(item, next)
    },
    // 自定义上传实现
    uploadBySelf(file, next = true) {
      this.uploading = true
      const fileInfo = this.listBox.filter(item => item.uid == file.uid)[0]
      this.$set(fileInfo, 'status', 'uploading')
      const form = new FormData()
      form.append('file', fileInfo.raw)
      request({
        url: modulePath + '/files-anon',
        method: 'post',
        data: form,
        onUploadProgress: (event) => {
          const percent = (event.loaded / event.total * 100) || 0
          this.$set(fileInfo, 'percentage', percent)
        }
      }).then(res => {
        if (res.data.resp_code === 0) {
          // this.$set(fileInfo, 'success', 0)
          // this.$set(fileInfo, 'status', 'success')
          this.uploadfile(res.data.datas, fileInfo, next)
        } else {
          this.uploading = false
          this.$set(fileInfo, 'status', 'fail')
          if (next) {
            this.uploadList.splice(0, 1)
            if (this.uploadList.length > 0) {
              this.uploadBySelf(this.uploadList[0])
            }
          }
          // this.toast.fail(file.name + '文件上传失败')
        }
      }).catch(err => {
        this.uploading = false
        this.toast.fail(file.name + '文件上传失败')
        console.log(err)
        this.$set(fileInfo, 'status', 'fail')
        if (next) {
          this.uploadList.splice(0, 1)
          if (this.uploadList.length > 0) {
            this.uploadBySelf(this.uploadList[0])
          }
        }
      })
    },
    // 上传参数校验
    validateParams() {
      const { bizType } = this.listUpload
      if (!bizType) {
        this.toast.fail('未选择上传类型')
        return false
      } else {
        if (bizType == '3' && (!this.hostId)) {
          this.toast.fail('未填写主持人ID')
          return false
        } else if (bizType == '1' && (!this.playId)) {
          return this.toast.fail('未选择期数ID')
        } else if (!this.listBox.every(item => ObjectUtil.notEmpty(item.cateList) === true)) {
          this.toast.fail('还有未选择标签的素材，先选择标签')
          return false
        }
      }
      return true
    },
    // 一键上传按钮点击处理
    submitUpload: Fn.Debounce(function() {
      if (!this.validateParams()) return
      // this.$refs.upload.submit()
      if (this.uploading) return
      if (this.uploadList.length > 0) {
        this.uploadBySelf(this.uploadList[0])
      }
    }),
    // 文件上传中的事件
    progress(event) {
      console.log(event, ';;;;;')
    },
    // 文件上传失败触发
    onError(err, file, filelist) {
      console.log(err + '上传失败')
      this.toast.fail(file.name + '文件上传失败')
      // this.$set(file,'success',2)
    },
    // 文件上传成功时的钩子
    successUpload(event, file, filelist) {
      console.log(file, 'success')
    },
    change(file, fileList) {
      const self = this
      this.loading = this.$loading({
        lock: true,
        text: `载入中...`,
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      this.count += 1 // count === 单次添加的文件个数
      const fileInfo = file
      if (fileInfo.status == 'ready') {
        const url = URL.createObjectURL(file.raw)
        const audioElement = new Audio(url)
        audioElement.addEventListener('loadedmetadata', function() {
          self.duration = audioElement.duration.toFixed(0) // playTime就是当前视频长度
          self.$set(fileInfo, 'duration', self.duration)
          self.listBox.push({ ...fileInfo, keywords: self.defaultkeywords })
          self.uploadList.push({ ...fileInfo, keywords: self.defaultkeywords })
          // 关闭loading窗的时机为count === 素材列表的长度
          if (self.count == self.listBox.length) {
            self.loading.close()
          }
        })
      }
    },

    // 上传到媒资
    uploadfile(data, file, next = true) {
      const videoDom = document.createElement('video')
      const videoBox = document.getElementsByClassName('videobox')[0]
      videoDom.crossOrigin = '*'
      videoDom.src = data.url
      videoDom.style.width = '0px'
      videoDom.style.height = '0px'
      videoDom.controls = 'true'
      videoDom.preload = 'auto'
      videoBox.appendChild(videoDom)
      // debugger
      this.$nextTick(() => {
        const ready = () => {
          const index = file.name.lastIndexOf('.')
          const name = file.name.slice(0, index)
          const { loc } = this.listUpload
          const { cateOneList, cateTwoList } = this.formatCate(1, file.cateList)
          const uploadInfo = {
            ...this.listUpload,
            url: data.url,
            duration: file.duration,
            size: file.size,
            title: name,
            prov: loc[0],
            loc: loc[1],
            cateOneList,
            cateTwoList,
            cateList: undefined,
            keywords: file.keywords ? file.keywords : ''
          }
          if (uploadInfo.bizType == 1) {
            this.$set(uploadInfo, 'playId', this.playId)
          } else if (uploadInfo.bizType == 3) {
            this.$set(uploadInfo, 'hostId', this.hostId)
          }
          const upload = () => {
            apiMeterial.batchUpload(uploadInfo).then(res => {
              if (res.data.resp_code === 0) {
                this.toast.success('上传成功')
                // 测试封面图
                // let obj = {u:uploadInfo.posterUrl,n:file.name}
                // this.test.push(obj)
                this.$set(file, 'status', 'success')
                // this.$set(file, 'success', 1)
                videoBox.innerHTML = ''
              } else {
                this.$set(file, 'status', 'fail')
                this.toast.fail(res.data.resp_msg)
              }
              this.uploading = false
              if (next) {
                this.uploadList.splice(0, 1)
                if (this.uploadList.length > 0) {
                  this.uploadBySelf(this.uploadList[0])
                }
              }
            }).catch(err => {
              console.log(err)
              this.uploading = false
              this.$set(file, 'status', 'fail')
              if (next) {
                this.uploadList.splice(0, 1)
                if (this.uploadList.length > 0) {
                  this.uploadBySelf(this.uploadList[0])
                }
              }
            })
          }
          const posterurl = this.clipImage(videoDom)
          console.log(posterurl)
          // debugger
          if (posterurl.match(/^data\:image/g)) {
            FileUtil.base64ToBolb(Common._randomString(12) + '.png', posterurl).then(res => {
              FileUtil.updateLoadFile(res).then(res => {
                const data = res.data.datas
                if (ObjectUtil.notNull(data) && ObjectUtil.notNull(data.url)) {
                  uploadInfo.posterUrl = data.url
                  console.log(data.url)
                  upload()
                }
              })
            })
          } else {
            upload()
          }
        }
        videoDom.addEventListener('loadeddata', () => {
          this.$nextTick(() => {
            console.log('加载完了')
            setTimeout(() => {
              ready()
            }, 1000)
          })
        })
      })
    },
    // 截图
    clipImage(videoDom) {
      const canvas = document.createElement('canvas')
      const canvasCtx = canvas.getContext('2d')
      const video = videoDom
      const rW = video.videoWidth
      const rH = video.videoHeight
      let tW, tH
      const target = 720
      if (rW > rH) {
        tW = target
        tH = Common.video2Equalratio(rW, rH, target)
      } else {
        tW = Common.video2Equalratio(rW, rH, target)
        tH = target
      }
      canvas.width = tW
      canvas.height = tH
      canvasCtx.drawImage(video, 0, 0, tW, tH)
      const dataUrl = canvas.toDataURL('image/png')
      return dataUrl
    },
    // 新建上传
    newUplaod: Fn.Confirm(function() {
      this.reload()
    },
    '是否删除当前内容并新建？'),
    // 删除视频
    del_video(item, i) {
      if (this.uploadList.length > 0) {
        this.uploadList.forEach((list, index) => {
          if (list.uid == item.uid) {
            this.uploadList.splice(index, 1)
          }
        })
      }
      this.listBox.splice(i, 1)
      this.count -= 1
      //
    },
    // 重置页面
    refresh() {
      this.reload()
    },
    // 搜索期数id
    getSearch() {
      if (!this.playId) return this.toast.fail('输入期数ID')
      apiMeterial.searchPeriodId({ playId: this.playId }).then(res => {
        if (res.data.resp_code === 0) {
          const result = res.data.datas || {}
          if (ObjectUtil.notEmpty(result)) {
            const { radioName, channelName, programmeName, liveHostsName, loc, prov } = result
            const keywords = [radioName, channelName, programmeName, liveHostsName].join(',') || ''
            this.defaultkeywords = keywords.slice(0, keywords.lastIndexOf(','))
            this.listBox = this.listBox.map(item => {
              return {
                ...item,
                keywords: this.defaultkeywords
              }
            })
            this.listUpload.loc = [Number(prov), Number(loc)]
          } else {
            this.defaultkeywords = ''
          }
        }
      }).catch(err => console.log(err))
    },
    // 初始化页面
    Init() {
      this.getAreaList()
      this.relationCategory()
    }
  }
}
</script>

<style lang='scss' scoped>
  .otherCss{
    .btnbox{
      margin: 20px 0;
    }
    .content{
      width:100%;
      height:auto;
      display: flex;
      justify-content: space-around;
      .left,.right{
        border:1px solid #ccc;
        // flex: 1;
        margin:0 10px;
        padding:15px;

      }
      .left{
        width:30%;
        .list{
          p{
            overflow: hidden;
            padding:10px 6px;
            & span:first-child{
              float: left;
            }
            & span:last-child{
              float: right;
            }
            // display: flex;
            // justify-content: space-around;
          }
        }
      }
      .right{
        width:60%;
        background: blue;
        .list{
          width:100%;
          p{
            overflow: hidden;
            padding:10px 6px;
            width:100%;
            display: flex;
            justify-content: space-around;
          }
        }
      }
    }
    .item{
      margin:20px 0;

    }

    .cate{
      display: flex;
      flex-wrap: wrap;
      align-items: center;

      .cate_list{
        display: flex;
        flex-wrap: wrap;
        align-items: center;

        .list{
          display: flex;
          // flex-direction: column;
          justify-content: center;
          align-items: center;
          .select{
            width:150px;
            margin-right: 10px;
            margin-bottom: 5px;
          }
        }
      }
    }
    tr{
      height: 30px;
      line-height: 30px;
    }
    tr td{
      text-align: center;
    }
  }

</style>
<style>
  .cate.el-form-item .el-form-item__content{
        margin-left: 0px !important;
      }
</style>
